package com.yt.fras.aop;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * ClassName:WebLogAspect
 * Package:com.yt.fras.aop
 * Description:
 * web请求日志
 *
 * @date:2021/8/15 15:12
 * @author:yt
 */

@Aspect
@Component
@Slf4j
public class WebLogAspect {

    /**
     * 切入点 * com.yt.controller 包下的所有类
     * * 该类中的所有方法
     * (..) 所有的方法参数
     */
    @Pointcut("execution(public * com.yt.fras.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 前置通知，请求方法之前做拦截
     *
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        log.info("URL : " + request.getRequestURL().toString());
        log.info("HTTP_METHOD : " + request.getMethod());
        log.info("IP : " + request.getHeader("X-Real-IP"));
        log.info("Class：" + joinPoint.getSignature().getDeclaringTypeName() + "\r");
        log.info("Method：" + joinPoint.getSignature().getName() + "\r");
    }

    /**
     * 目标方法请求之后 打印 (响应信息)
     *
     * @param ret
     * @throws Throwable
     */
    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("RESPONSE : " + ret);
    }
}